#!/bin/sh

export PATH=$PATH:/usr/svcagent/bin:/usr/bin:/etc:/usr/sbin:/usr/ucb:/usr/bin/X11:/sbin:/local/bin:/usr/dt/bin:/opt/IBMJava2-13/bin:/usr/java130/bin:/opt/IBMJava2-13/jre/bin

upflg=0
#check for existing processess.
ps wax --cols 400| grep "ibm/ecf/apps/ESS" | grep -v grep >/dev/null 2>&1 || ps wax --cols 400| grep "ibm.ecf.apps.ESS" | grep -v grep >/dev/null 2>&1
[ $? -eq 0 ]  && ckess="Already Started" && upflg=1 
ps wax --cols 400| grep "ibm/ecf/apps/ODS" | grep -v grep >/dev/null 2>&1 || ps wax --cols 400| grep "ibm.ecf.apps.ODS" | grep -v grep >/dev/null 2>&1
[ $? -eq 0 ] && ckods="Already Started" && upflg=1
[ $upflg -eq 1 ] && echo "ODS $ckods, ESS $ckess - Stop Gateway first before starting." && exit -1

echo "Starting the ESS process ...." 

#Check if the ESS entry is already there in the inittab or else, create an entry for ESS.

INITTABFILE=/etc/inittab
OURSTRING=svcagent
TMPFILE=/tmp/svc.init
sed -e "/^[^:]*:[^:]*:[^:]*:[^#]*$OURSTRING/d" $INITTABFILE  >$TMPFILE || exit 2cp $TMPFILE $INITTABFILE
rm $TMPFILE
echo "svc:2345:respawn:su - svcagent /usr/svcagent/bin/ess" >>$INITTABFILE
echo "svc1:2345:respawn:su - svcagent /usr/svcagent/bin/ods" >>$INITTABFILE
echo "svc2:2345:respawn:su - svcagent /usr/svcagent/bin/sares" >>$INITTABFILE


sleep 2
telinit q

echo "Starting the ODS process ...."
rm /var/svcagent/elh.dtim > /dev/null 2>&1
sleep 3
ckess="Waiting"
ckods="Waiting"
a=5
b=60 # max wait before timeout
while [ "$ckess." = "Waiting." -o  "$ckods." = "Waiting." ]
do
	ps wax --cols 400 | grep "ibm/ecf/apps/ESS" | grep -v grep >/dev/null 2>&1
	[ $? -eq 0 ]  && ckess="Started"
	ps wax  --cols 400| grep "ibm.ecf.apps.ESS" | grep -v grep >/dev/null 2>&1
	[ $? -eq 0 ]  && ckess="Started"
	ps wax  --cols 400| grep "ibm/ecf/apps/ODS" | grep -v grep >/dev/null 2>&1
	[ $? -eq 0 ] && ckods="Started"
	ps wax  --cols 400| grep "ibm.ecf.apps.ODS" | grep -v grep >/dev/null 2>&1
	[ $? -eq 0 ] && ckods="Started"
	echo "ODS $ckods, ESS $ckess, time = $a seconds"
	sleep 5
	let "a = $a +5"
	if [ "$a" -gt "$b" ]
	then
                grep "Insufficient disk space in /var to Run the Service Agent Application" /var/svcagent/logs/stat.ess
                if [ "$?" = "0" ]
                then
                  echo "ESS might not have started due to Insufficeint Disk Space in /var"
                else

		echo "Waiting process is failing to start, please check /etc/inittab"
                fi
		exit -1
	fi
done
echo "All processes running "
sleep 2
echo " "
